import 'dart:async';
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/common/action/filter/index.dart';
import 'package:qgchat/common/class/eventBus/index.dart';
import 'package:qgchat/common/class/sql/Sql.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/page/msg/msg/index.dart';
import 'package:qgchat/states/states_model/socket.dart';
import 'package:qgchat/states/states_model/user.dart';
import 'package:qgchat/widgets/tipsDialog.dart';

import 'home.dart';
import 'my/my/my.dart';

class AppBottomBars extends StatefulWidget {
  AppBottomBars({Key key}) : super(key: key);

  _AppBottomBarsState createState() => _AppBottomBarsState();
}

class _AppBottomBarsState extends State<AppBottomBars>
    with WidgetsBindingObserver {
  int _currentIndex = 0;
  List<Widget> pages = [
    Home(),
    // VideoBar(),
    MsgIndex(),
    My(),
  ];

  List tabBarList = [
    {
      'title': '直播',
      'icon': 'assets/images/tab/u1.png',
      'activeIcon': 'assets/images/tab/t1.png',
    },
    // {
    //   'title': '视频',
    //   'icon': 'assets/images/tab/u2.png',
    //   'activeIcon': 'assets/images/tab/t2.png',
    // },
    {
      'title': '消息',
      'icon': 'assets/images/tab/u3.png',
      'activeIcon': 'assets/images/tab/t3.png',
    },
    {
      'title': '我的',
      'icon': 'assets/images/tab/u4.png',
      'activeIcon': 'assets/images/tab/t4.png',
    },
  ];

  /// 未读状态
  bool isNotRead = false;

  @override
  void initState() {
    super.initState();
    if (mounted) {
      WidgetsBinding.instance.addObserver(this); // 监听app状态
      Timer(Duration(milliseconds: 500), () {
        _handleCameraAndMic();
      });

      bus.on('homeTabbarIndex', (i) {
        if (i is int && i < pages.length) {
          _currentIndex = i;
          setState(() {});
        }
      });

      bus.on(
        'changeReadStatus',
        (val) async {
          if (!mounted) return;
          final info = Provide.value<UserState>(context).info;
          isNotRead = await Sql().queryUnRead(info.memberToken);
          setState(() {});
        },
      );

      // 以下两个timer
      // 为了解决奇怪的第一次加载的页面不出来的问题
      // 如果有其他解决办法 这里可以删掉
      Timer(
        Duration(milliseconds: 300),
        () {
          _currentIndex = 1;
          setState(() {});
        },
      );
      Timer(
        Duration(milliseconds: 500),
        () {
          _currentIndex = 0;
          setState(() {});
        },
      );
    }
  }

  // 获取权限
  _handleCameraAndMic() async {
    // 申请权限
    await PermissionHandler().requestPermissions([
      PermissionGroup.camera,
      PermissionGroup.microphone,
      PermissionGroup.storage,
      PermissionGroup.locationWhenInUse,
    ]);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: // 应用程序可见，前台
        print('前台');
        Global?.ws?.reconnect();
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        print('后台');
        break;
      case AppLifecycleState.detached: // 申请将暂时暂停
        break;
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // 销毁监听app状态
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        bool userChoiceClose = false;
        await TipsDialog.tryCloseApp(
          context,
          () => userChoiceClose = true,
        );
        return Future.value(userChoiceClose);
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        body: pages[_currentIndex],
        bottomNavigationBar: Stack(
          children: <Widget>[
            BottomNavigationBar(
              type: BottomNavigationBarType.fixed,
              currentIndex: _currentIndex,
              backgroundColor: Colors.white,
              selectedItemColor: col("4bd5e2"),
              unselectedItemColor: col("606266"),
              selectedFontSize: 12.0,
              onTap: (int index) {
                setState(() {
                  _currentIndex = index;
                });
              },
              items: items(),
            ),
            Positioned(
              top: px(10),
              right: px(240),
              child: stateBuilder(context, 'socket', (SocketState socket) {
                return Badge(showBadge: isNotRead);
                return tipsCount(socket.chatList.fold(0, (preValue, item) {
                  return preValue + item.readCount;
                }));
              }),
            ),
          ],
        ),
      ),
    );
  }

  List<BottomNavigationBarItem> items() {
    return tabBarList.asMap().keys.map<BottomNavigationBarItem>((i) {
      List<Widget> list = [
        Image.asset(
          tabBarList[i]["icon"],
          height: px(44),
        ),
      ];
      List<Widget> activelist = [
        Image.asset(
          tabBarList[i]["activeIcon"],
          height: px(44),
        ),
      ];
      return BottomNavigationBarItem(
        icon: Stack(
          children: list,
        ),
        activeIcon: Stack(
          children: activelist,
        ),
        title: Container(
          margin: EdgeInsets.only(top: px(10)),
          child: Text(tabBarList[i]["title"]),
        ),
      );
    }).toList();
  }

  // 红色小圆点
  Widget tipsCount(int count) {
    if (count > 0) {
      return ConstrainedBox(
        constraints: BoxConstraints(
          minWidth: px(36),
          minHeight: px(36),
        ),
        child: Container(
          height: px(36),
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(
            horizontal: px(10),
          ),
          decoration: BoxDecoration(
            color: col("ff3b30"),
            borderRadius: BorderRadius.circular(
              px(18),
            ),
          ),
          child: Text(
            "${Filter.maxToAdd(count, 99)}",
            style: TextStyle(
              color: Colors.white,
              fontSize: px(26),
            ),
          ),
        ),
      );
    } else {
      return Container();
    }
  }
}
